package com.priusoft.api.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.priusoft.api.common.JwtUtil;
import com.priusoft.api.domain.AjaxResult;
import com.priusoft.api.entity.CapUser;
import com.priusoft.api.service.CapUserService;
import com.priusoft.api.common.crypto.DESedeUserPasswordCipher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;

@CrossOrigin
@Controller
public class LoginController {

    @Autowired
    private CapUserService capUserService;

    // 请求示例 http://localhost:8082/login?userid=wangzelong&password=000000&cipher=0
    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult Login(String userid, String password, Integer cipher) throws Exception {
        AjaxResult result;
        QueryWrapper<CapUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userid);
        CapUser one = capUserService.getOne(wrapper);
        if (one == null) {
            result = AjaxResult.error("用户名不存在");
        } else {
            String _password = one.getPassword();
            if(cipher==0) { //如果是明文的话，需要对密码加密处理
                password = DESedeUserPasswordCipher.encrypt(password);
            }
            if (password.equals(_password)) {
                result = AjaxResult.success("登录成功");

                String token = JwtUtil.createToken(userid);
                result.put("data",token);
            } else {
                result = AjaxResult.error("用户名或密码输入有误");
            }
        }

        return result;
    }
}
